package com.xjscrm.server.service.wwgroupmember.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.msg.*;
import com.uzai.mobile.collect.api.dto.trigger.group.MicaTriggerGroupKickMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.biz.mq.producer.SendMsgProducer;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.Functions;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.customer.WwCustomerTagsService;
import com.xjscrm.server.service.wwgroupmember.WwGroupMemberService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 企业微信群成员实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class WwGroupMemberServiceImpl implements WwGroupMemberService {

    @Autowired
    private WwGroupMapper wwGroupMapper;
    @Autowired
    private WwGroupMemberMapper wwGroupMemberMapper;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private TaskTagAutoMapper taskTagAutoMapper;
    @Autowired
    private TaskTagAutoDeviceMapper taskTagAutoDeviceMapper;
    @Autowired
    private WwTagsMapper wwTagsMapper;
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private WwCustomerTagsService wwCustomerTagsService;
    @Autowired
    private WwCustomerBlacklistMapper wwCustomerBlacklistMapper;
    @Autowired
    private SendMsgProducer sendMsgProducer;
    @Autowired
    private RatelimitService ratelimitService;

    /**
     * 同步企业微信群
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void wwGroupMemberPush(MicaTransDto micaTransDto) {

        //限流判断(同一个机器人60秒之内只能操作一次)
//        String rateLimitKey = "wwGroupMemberPush-taskId=" + micaTransDto.getDeviceId();
//        boolean inRateLimit = ratelimitService.inRateLimit(rateLimitKey, 1, 60);
//        if (!inRateLimit) {
//            return;
//        }

        try {
            log.info("--监控系统日志--开始--");
            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人的配置方案
            log.info("--监控系统日志--查询机器人--");
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //更新时间
            int now = DateUtil.getTime();

            MicaConversationMemberMsg micaConversationMemberMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaConversationMemberMsg.class);
            if (micaConversationMemberMsg != null) {

                //群微信id
                String groupId = micaConversationMemberMsg.getGroupId();
                //查询该群存不存在
                log.info("--监控系统日志--查询群--");
                WwGroup wwGroup = wwGroupMapper.queryByDeviceUniqueIdAndGroupWxid(device.getDeviceUniqueId(), groupId);
                if (wwGroup == null) {
                    log.info("群不存在, groupWxid={}", groupId);
                    return;
                }

                //查询此群群主
                String createWxid = wwGroup.getCreateWxid();
                //查询此群的管理人员
                List<String> adminWxIdList = JSONObject.parseArray(wwGroup.getAdminWxIds(), String.class);
                if(adminWxIdList == null){
                    adminWxIdList = new ArrayList<>();
                }

                List<MicaConversationMemberMsg.ConversationMemberMsg> members = micaConversationMemberMsg.getMembers();
                if (members != null && members.size() > 0) {
                    for (MicaConversationMemberMsg.ConversationMemberMsg memberMsg : members) {
                        //判断存不存在，不存在则添加
                        WwGroupMember wwGroupMember = wwGroupMemberMapper.selectByGroupWxidAndWxid(device.getMerId(), groupId, memberMsg.getWxid());
                        if (wwGroupMember == null) {
                            wwGroupMember = new WwGroupMember();
                            wwGroupMember.setId(IdWorker.getId());
                            wwGroupMember.setMerId(device.getMerId());
                            wwGroupMember.setGroupWxid(groupId);
                            wwGroupMember.setWxid(memberMsg.getWxid());
                            wwGroupMember.setNick(memberMsg.getNick());
                            wwGroupMember.setNickRemark(memberMsg.getNickRemark());
                            wwGroupMember.setHimg(memberMsg.getHimg());
                            wwGroupMember.setRemark(null);
                            wwGroupMember.setInviterWxid(memberMsg.getInviterWxid());
                            //是否是机器人
                            WwDevice wwDevice_wxid = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
                            if (wwDevice_wxid == null) {
                                wwGroupMember.setType(0); //普通会员
                            } else {
                                wwGroupMember.setType(1); //机器人
                            }
                            wwGroupMember.setCorpId(memberMsg.getCorpId());

                            //身份（0-群主；1-管理员；2-普通成员）
                            Integer identity = 2;
                            //管理人员列表包含此成员，则是管理人员

                            if(Tools.getStr(memberMsg.getWxid()).equals(createWxid)){//判断是否是群主
                                identity = 0;
                            }else if(adminWxIdList.contains(memberMsg.getWxid())){//判断是否是管理人员
                                identity = 1;
                            }
                            wwGroupMember.setIdentity(identity);
                            wwGroupMember.setRecentSpeakTime(null);
                            wwGroupMember.setScene(null);
                            wwGroupMember.setCreateTime(now);
                            wwGroupMember.setUpdateTime(now);

                            wwGroupMemberMapper.insert(wwGroupMember);

                            log.info("--监控系统日志--查询群成员--");

                        } else {
//                            wwGroupMember.setNick(memberMsg.getNick());
//                            wwGroupMember.setNickRemark(memberMsg.getNickRemark());
//                            wwGroupMember.setHimg(memberMsg.getHimg());
//                            wwGroupMember.setRemark(null);
//                            wwGroupMember.setInviterWxid(memberMsg.getInviterWxid());
//                            //是否是机器人
//                            WwDevice wwDevice_wxid = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
//                            if (wwDevice_wxid == null) {
//                                wwGroupMember.setType(0); //普通会员
//                            } else {
//                                wwGroupMember.setType(1); //机器人
//                            }
//                            wwGroupMember.setCorpId(memberMsg.getCorpId());
//
//                            //身份（0-群主；1-管理员；2-普通成员）
//                            Integer identity = 2;
//                            //管理人员列表包含此成员，则是管理人员
//
//                            if(Tools.getStr(memberMsg.getWxid()).equals(createWxid)){//判断是否是群主
//                                identity = 0;
//                            }else if(adminWxIdList.contains(memberMsg.getWxid())){//判断是否是管理人员
//                                identity = 1;
//                            }
//                            wwGroupMember.setIdentity(identity);
//                            wwGroupMember.setRecentSpeakTime(null);
//                            wwGroupMember.setScene(null);
//                            wwGroupMember.setUpdateTime(now);
//                            wwGroupMemberMapper.updateById(wwGroupMember);

//                            log.info("--监控系统日志--修改群成员--");
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage() ,e);
        }finally {
            log.info("--监控系统日志--结束--");
        }

    }

    /**
     * 企业微信群成员进群
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void wwGroupMemberAdd(MicaTransDto micaTransDto) {
        try {
            log.info("--监控系统日志--开始--");

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人
            log.info("--监控系统日志--查询机器人--");
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //更新时间
            int now = DateUtil.getTime();

            MicaGroupMemberAddMsg micaGroupMemberAddMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaGroupMemberAddMsg.class);
            if (micaGroupMemberAddMsg != null) {

                //群微信id
                String groupId = micaGroupMemberAddMsg.getGroupId();
                //查询该群存不存在
                log.info("--监控系统日志--查询群--");
                WwGroup wwGroup = wwGroupMapper.queryByDeviceUniqueIdAndGroupWxid(device.getDeviceUniqueId(), groupId);
                if (wwGroup == null) {
                    log.info("群不存在, groupWxid={}", groupId);
                    return;
                }

                //查询此群群主
                String createWxid = wwGroup.getCreateWxid();
                //查询此群的管理人员
                List<String> adminWxIdList = JSONObject.parseArray(wwGroup.getAdminWxIds(), String.class);
                if(adminWxIdList == null){
                    adminWxIdList = new ArrayList<>();
                }

                List<MicaGroupMemberItemMsg> members = micaGroupMemberAddMsg.getMembers();
                if (members != null && members.size() > 0) {
                    for (MicaGroupMemberItemMsg memberMsg : members) {

                        //默认黑名单不通过
                        WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(micaTransDto.getMerId(), memberMsg.getWxid());
                        if(wwCustomerBlacklist != null){ //在黑名单中
                            //删除所有的群内黑名单成员
                            wwGroupMemberMapper.deleteByWxid(device.getMerId(), memberMsg.getWxid());
                            //发送踢人指令
                            MicaTriggerGroupKickMsg micaTriggerGroupKickMsg = new MicaTriggerGroupKickMsg();
                            micaTriggerGroupKickMsg.setGroupId(groupId);
                            micaTriggerGroupKickMsg.setWxIds(memberMsg.getWxid());
                            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupKickMsg, MicaTriggerType.TRIGGER_GROUP_KICK, Functions.fillTriggerMsg(device));
                            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC); //存放瞬时消息
                        }else{
                            //判断存不存在，不存在则添加
                            WwGroupMember wwGroupMember = wwGroupMemberMapper.selectByGroupWxidAndWxid(device.getMerId(), groupId, memberMsg.getWxid());
                            if (wwGroupMember == null) {
                                wwGroupMember = new WwGroupMember();
                                wwGroupMember.setId(IdWorker.getId());
                                wwGroupMember.setMerId(device.getMerId());
                                wwGroupMember.setGroupWxid(groupId);
                                wwGroupMember.setWxid(memberMsg.getWxid());
                                wwGroupMember.setNick(memberMsg.getNickname());
                                wwGroupMember.setNickRemark(null);
                                wwGroupMember.setHimg(null);
                                wwGroupMember.setRemark(null);
                                wwGroupMember.setInviterWxid(memberMsg.getOptWxId());
                                //是否是机器人
                                WwDevice wwDevice_wxid = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
                                if (wwDevice_wxid == null) {
                                    wwGroupMember.setType(0); //普通会员
                                } else {
                                    wwGroupMember.setType(1); //机器人
                                }
                                wwGroupMember.setCorpId(memberMsg.getCorpId());
                                //身份（0-群主；1-管理员；2-普通成员）
                                Integer identity = 2;
                                //管理人员列表包含此成员，则是管理人员

                                if(Tools.getStr(memberMsg.getWxid()).equals(createWxid)){//判断是否是群主
                                    identity = 0;
                                }else if(adminWxIdList.contains(memberMsg.getWxid())){//判断是否是管理人员
                                    identity = 1;
                                }
                                wwGroupMember.setIdentity(identity);
                                wwGroupMember.setRecentSpeakTime(null);
                                wwGroupMember.setScene(null);
                                wwGroupMember.setCreateTime(now);
                                wwGroupMember.setUpdateTime(now);
                                wwGroupMemberMapper.insert(wwGroupMember);

                                log.info("--监控系统日志--插入群成员--");
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage() ,e);
        }finally {
            log.info("--监控系统日志--结束--");
        }

    }

    /**
     * 企业微信群成员退群
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void wwGroupMemberDel(MicaTransDto micaTransDto) {
        try {
            log.info("--监控系统日志--开始--");

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人
            log.info("--监控系统日志--查询机器人--");
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //更新时间
            int now = DateUtil.getTime();

            MicaGroupMemberDelMsg micaGroupMemberDelMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaGroupMemberDelMsg.class);
            if (micaGroupMemberDelMsg != null) {

                //群微信id
                String groupId = micaGroupMemberDelMsg.getGroupId();
                //查询该群存不存在
                WwGroup wwGroup = wwGroupMapper.queryByDeviceUniqueIdAndGroupWxid(device.getDeviceUniqueId(), groupId);
                if (wwGroup == null) {
                    log.info("群不存在, groupWxid={}", groupId);
                    return;
                }

                List<MicaGroupMemberItemMsg> members = micaGroupMemberDelMsg.getMembers();
                if (members != null && members.size() > 0) {
                    for (MicaGroupMemberItemMsg memberMsg : members) {
                        //判断存不存在，不存在则添加
                        WwGroupMember wwGroupMember = wwGroupMemberMapper.selectByGroupWxidAndWxid(device.getMerId(), groupId, memberMsg.getWxid());
                        if (wwGroupMember != null) {
                            wwGroupMemberMapper.deleteById(wwGroupMember.getId());
                            log.info("--监控系统日志--删除群成员--");
                        }
                    }
                }
            }

        }catch (Exception e){
            log.error(e.getMessage() , e);
        }finally {
            log.info("--监控系统日志--结束--");
        }

    }

}
